<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/18
 * Time: 22:28
 * @link http://www.lmterp.cn
 */

namespace app\common\service\system;


use app\common\library\Tools;
use app\common\model\SysAttachment;
use app\common\model\SysCountries;
use app\common\model\SysExchange;
use app\common\model\SysTrash;
use app\common\service\BaseService;
use think\Db;
use think\facade\Log;

class SystemService extends BaseService
{
    /**
     * 清空回收站指定天数的数据
     * @param int $day 具体的天数，默认 60天
     * @return bool
     * @date 2020/09/18
     * @author longli
     */
    public function clearTrash($day = 60)
    {
        if($day < 0) return false;
        $date = date('Y-m-d', strtotime("-{$day}day"));
        try
        {
            return SysTrash::where("create_time", "<=", $date)->delete() > 0;
        } catch (\Exception $e){}
        return false;
    }

    /**
     * 恢复回收站数据
     * @param int|int[] $ids 回收站 id
     * @return bool
     * @date 2020/09/18
     * @author longli
     */
    public function recover($ids = [])
    {
        if(!is_array($ids)) $ids = explode(",", $ids);
        try
        {
            Db::startTrans();
            foreach(SysTrash::where("trash_id", "in", $ids)->select() as $item)
            {
                Db::table($item->tablename)->insert(unserialize($item->getData('data')), true);
                $item->delete();
            }
            Db::commit();
            return true;
        }catch(\Exception $e)
        {
            Db::rollback();
            Log::info(sprintf("回收站恢复失败，失败信息【%s】", $e->getMessage()));
        }
        return false;
    }

    /**
     * 添加国家
     * @param array $data 国家信息
     * @return SysCountries|bool
     * @date 2020/09/20
     * @author longli
     */
    public function addCountry($data = [])
    {
        $cData = SysCountries::getFilterField($data, '');
        if(empty($cData)) return false;
        $cData = Tools::trim($cData);
        $country = null;
        foreach(['code_two', 'code_three', 'currency_code'] as $v)
            if(isset($cData[$v])) $cData[$v] = strtoupper($cData[$v]);
        if(isset($cData['country_id'])) $country = SysCountries::get($cData['country_id']);
        if(!empty($country))
        {
            $country->save($cData);
        }
        else
        {
            if(isset($cData['continent_en']))
                $cData['continent_ch'] = SysCountries::get(['continent_en'=>$cData['continent_en']])->continent_ch;
            $country = SysCountries::create($cData)->refresh();
        }
        return $country;
    }

    /**
     * 添加汇率
     * @param array $data 汇率信息
     * @return SysExchange|bool
     * @date 2020/09/20
     * @author longli
     */
    public function addExchange($data = [])
    {
        $eData = SysExchange::getFilterField($data, '');
        if(empty($eData)) return false;
        if(isset($eData['source_code']) && empty($eData['source_name']))
            $eData['source_name'] = SysCountries::get(['currency_code' => $eData['source_code']])->currency_name;
        if(isset($eData['target_code']) && empty($eData['target_name']))
            $eData['target_name'] = SysCountries::get(['currency_code' => $eData['target_code']])->currency_name;
        $exchange = null;
        if(isset($eData['exchange_id'])) $exchange = SysExchange::get($eData['exchange_id']);
        if(empty($exchange) && isset($eData['source_code']) && $eData['target_code'])
            $exchange = SysExchange::get(['source_code' => $eData['source_code'], 'target_code' => $eData['target_code']]);
        if(!empty($exchange))
        {
            $exchange->save($eData);
        }
        else
        {
            $exchange = SysExchange::create($eData)->refresh();
        }
        return $exchange;
    }

    /**
     * 汇率兑换
     * @param string $sourceCode 源兑换币种代码
     * @param float|int $money 需要兑换的金额
     * @param string $targetCode 目标兑换币种代码，默认人民币CNY
     * @return float 如果返回 0 则是没有兑换成功
     * @date 2020/09/20
     * @author longli
     */
    public function exchangeRate($sourceCode, $money = 1, $targetCode = 'CNY')
    {
        if($sourceCode == $targetCode) return $money;
        if($money == 0) return 0;
        if(!($e = SysExchange::get(['source_code' => $sourceCode, 'target_code' => $targetCode]))) return 0;
        return $e->rate * $money;
    }

    /**
     * 添加附件
     * @param string[] $data 附件信息
     * @return bool
     * @date 2020/12/18
     * @author longli
     */
    public function addAttachment($data = [])
    {
        $adata = SysAttachment::getFilterField($data, '');
        if(empty($adata)) return false;
        $adata = Tools::trim($adata);
        if(!empty($adata['path']))
        {
            $rootPath = self::getRootPath($adata['path']);
            if(is_file($rootPath)) $adata['md5_code'] = md5_file($rootPath);
        }
        if(!empty($adata['md5_code']) && SysAttachment::hasFile($adata['md5_code'])) return false;
        $attachment = null;
        if(isset($adata['attach_id'])) $attachment = SysAttachment::get($adata['attach_id']);
        if(!empty($attachment))
        {
            $attachment->save($adata);
        }
        else
        {
            SysAttachment::create($adata);
        }
        return true;
    }

    /**
     * 批量添加附件信息
     * @param string $idType 业务主表
     * @param int $refId 业务主表id
     * @param array $data 附件信息
     * @date 2020/12/19
     * @author longli
     */
    public function addAttachments($idType, $refId, $data = [])
    {
        $type = [
           'contract' => SysAttachment::FILE_TYPE_CONTRACT,
           'invoice' => SysAttachment::FILE_TYPE_INVOICE,
           'other' => SysAttachment::FILE_TYPE_OTHER,
        ];
        $flag = false;
        $data = Tools::trim($data);
        foreach($data as $key => $value)
        {
            if(!isset($type[$key]) || empty($value)) continue;
            $flag = true;
            if(is_string($value)) $value = explode(',', $value);
            foreach($value as $path)
            {
                $path = trim($path);
                if(empty($path)) continue;
                $this->addAttachment([
                    'id_type' => $idType,
                    'ref_id' => $refId,
                    'path' => $path,
                    'type' => $type[$key],
                ]);
            }
        }
        return $flag;
    }
}